import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Pagination, ConfirmService, ToastService, ModalService } from 'ng-tui';
import { ApiData, SearchParams } from '../../../../cores/classes';
import { GlobalService } from '../../../../cores/services';
import { AccountService } from '../../services/account.service';
import { Price } from './../../interfaces/inventory.interfaces';
import { skipWhile, switchMap } from 'rxjs/operators';
import { ModalpicetComponent } from './modalpice.component';

@Component({
    selector: 'app-price',
    templateUrl: './price.component.html',
    styleUrls: ['./price.component.scss']
})
export class PriceComponent implements OnInit {

    theads = ['#', '账户名称', '账户类型', '账户余额', '期初日期', '操作'];

    search = new SearchParams({ start: '', end: '' });

    list = new Array<Price>();
    price: Price = {};
    loading = false;

    pagination = new Pagination();

    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        public global: GlobalService,
        private confirm: ConfirmService,
        private accountService: AccountService,
        private toast: ToastService,
        private modal: ModalService,
    ) { }

    ngOnInit() {
        this.activatedRoute.url
            .pipe(skipWhile(() => this.router.url !== '/admin/platform'))
            .subscribe(() => this.loadDatas());
        this.loadDatas();
    }

    doSearch() {
        this.pagination.reset();
        this.loadDatas();
    }

    doReset() {
        this.search.clean();
        this.doSearch();
    }

    loadDatas() {
        this.loading = true;
        this.accountService.surpluslist(this.pagination, this.search).subscribe({
            next: res => {
                this.pagination.total = res.datas.total;
                this.list = res.datas.rows;
            },
            complete: () => this.loading = false
        });
    }

    showEditModal(item: Price) {
        const modal = this.modal.create(ModalpicetComponent, { center: true });
        modal.instance.price = Object.assign(modal.instance.price, item);
        modal.open().subscribe(() => {
            this.toast.success('保存成功', '成功保存余额');
            this.loadDatas();
        });
    }
    confirmDelete(id: number) {
        this.confirm.danger('删除确认', `您确认删除余额数据'吗？`)
            .pipe(switchMap<void, ApiData>(() => this.accountService.deleltsurplurs(id)))
            .subscribe(() => {
                this.list.splice(this.list.indexOf(this.price), 1);
                this.toast.success('删除成功', `成功删除余额数据`);
                this.loadDatas();
            });
    }
}
